#!/usr/bin/env ruby
# frozen_string_literal: true

require 'optparse'
require 'yaml'
require_relative 'lib/shell'
require_relative 'lib/loadenv'

def load_commands(dir, group = nil)
  description_file = File.join(__dir__, dir, 'description.yaml')
  descriptions = File.exist?(description_file) ? YAML.load(File.read(description_file)) : {}

  environments = {}
  Dir.children(File.join(__dir__, dir)).each do |command|
    next if command['.'] # 带有后缀名的文件不是子命令

    environments[command] = {
      path: File.join(__dir__, dir, command),
      description: descriptions[command],
      group: group
    }
  end

  environments
end

def print_help
  environments = @scripts.to_a.find_all { |command, options| options[:group] == 'environment' }.to_h
  subcommands = @scripts.to_a.find_all { |command, options| options[:group] == 'subcommand' }.to_h

  puts <<~END_DOC
    一键配置各种环境，现支持的脚本包括：

    #{
      environments.map { |command, options| '    ' + command + '    ' + (options[:description] || '') }.join("\n")
    }

    另有特殊的脚本，包括：

    #{
      subcommands.map { |command, options| '    ' + command + '    ' + (options[:description] || '') }.join("\n")
    }

  END_DOC
end

def execute_command(command)
  if @scripts.key?(command)
    exec @scripts[command][:path], *ARGV
  else
    shell.exit(Shell::Errors::COMMAND_NOT_FOUND, "未定义的一键安装命令：#{command}")
  end
end

LoadEnv.load_env
ARGV.push('--help') if ARGV.empty?

@scripts = load_commands('environments', 'environment')
           .merge(load_commands('commands', 'subcommand'))

command = ARGV.shift
if ['-h', '--help'].include?(command)
  print_help
else
  execute_command command
end
